package com.axend.aerosense.user.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.axend.aerosense.common.util.HeadIconUploadService;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.common.bean.UserIconBean;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.common.adapter.CommonBindingAdapters;
import com.axend.aerosense.common.bean.UserInfo;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.ui.BottomTextPickerDialog;
import com.axend.aerosense.common.ui.CustomInputDialog;
import com.axend.aerosense.user.BR;
import com.axend.aerosense.user.R;
import com.axend.aerosense.user.UserSettingActivity;
import com.axend.aerosense.common.util.UserImageEngine;
import com.axend.aerosense.user.databinding.UserCentryFragmentBinding;
import com.axend.aerosense.user.viewmodel.UserCentryViewModel;

import java.io.File;
import java.util.List;

public class UserCentryFragment extends MvvmBaseFragment<UserCentryFragmentBinding, UserCentryViewModel> {
    private CustomInputDialog customInputDialog;
    private UserInfo userInfo;
    private Bitmap bitmap;

    public static UserCentryFragment getInstance() {
        UserCentryFragment fragment = new UserCentryFragment();
//        Bundle bundle = new Bundle();
//        bundle.putString(ARG_PARAM, str);
//        fragment.setArguments(bundle);   //设置参数
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private void initView() {
        String[] stringArrary = getResources().getStringArray(R.array.common_sex_list);
        viewDataBinding.userHelpTitle.setText(stringArrary[userInfo.userSexType]);
        viewDataBinding.userHelpTitle.setOnClickListener(v -> {
            BottomTextPickerDialog fragment = new BottomTextPickerDialog.Builder()
                    .setType(Type.NUMBER)
                    .setWheelItemTextSize(16)
                    .setThemeColor(getResources().getColor(R.color.app_colorAccent))
                    .setIndexCallBack((f, index)->{
                        viewDataBinding.userHelpTitle.setText(stringArrary[index]);
                        viewModel.setSexTypeValue(index);
                        viewModel.onChangeSex(getActivity());
                    })
                    .build(stringArrary);
            fragment.show(getChildFragmentManager(), BottomTextPickerDialog.class.getSimpleName());
        });

        String imageSrc = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.IMAGE_ICON);
        //设置头像
        if (!TextUtils.isEmpty(imageSrc)) {
//            Log.d("myTAG", "initView:null------ userPersonIcon:" + MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.IMAGE_ICON));
            CommonBindingAdapters.imageCircleHeadUrl(viewDataBinding.userPersonIcon, MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.IMAGE_ICON),true);
        }
        //设置头像
        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.IMAGE_ICON_CHANGE, Integer.class)
                .observe(getViewLifecycleOwner(), temp -> {
//                    Log.d("myTAG", "initView:getViewLifecycleOwner----userPersonIcon:" + MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.IMAGE_ICON));
                    CommonBindingAdapters.imageCircleHeadUrl(viewDataBinding.userPersonIcon, MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.IMAGE_ICON),true);
                });

        viewDataBinding.userNickName.setOnClickListener(v -> {
            customInputDialog = new CustomInputDialog(getActivity(), getString(R.string.common_change_nickname)
                    /* , getString(R.string.common_nick_name_lenth)*/);
            customInputDialog.setMaxTextSize(8);
            customInputDialog.setOnClickBottomListener(new CustomInputDialog.OnClickBottomListener() {
                @Override
                public void onPositiveClick() {
                    String tmpNickName = customInputDialog.getInputValue();
                    if(TextUtils.isEmpty(tmpNickName)){
                        return;
                    }
                    viewModel.onChangeNickName(getActivity(), tmpNickName, new IOperationResult(){

                        @Override
                        public void onSuccess() {
                            viewModel.setNickValue(tmpNickName);
                        }

                        @Override
                        public void onFail() {

                        }
                    });
                    customInputDialog.dismiss();
                }

                @Override
                public void onNegtiveClick() {
                    customInputDialog.dismiss();
                }
            });
            customInputDialog.show();
        });

        viewDataBinding.userPersonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View inflate = LayoutInflater.from(getContext()).inflate(R.layout.user_head_popup_window, null);
                TextView tvPhoto = inflate.findViewById(R.id.user_tv_photo);  //调用照相机
                TextView tvAlbum = inflate.findViewById(R.id.user_tv_album);  //调用相册
                TextView tvCancel = inflate.findViewById(R.id.user_tv_cancel);

                final PopupWindow popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
                popupWindow.setOutsideTouchable(true);//设置外部可触摸
                popupWindow.setFocusable(true);//这里必须设置为true才能点击区域外或者消失
                popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                //得到父layout
                View parent = LayoutInflater.from(getActivity()).inflate(R.layout.user_centry_fragment, null);
                //展示在parent的下方，0,0的位置
                popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);

                //popupWindow在弹窗的时候背景半透明
                final WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();

                params.alpha = 0.5f;
                getActivity().getWindow().setAttributes(params);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        params.alpha = 1.0f;
                        getActivity().getWindow().setAttributes(params);
                    }
                });
                //拍照选择
                tvPhoto.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PictureSelector.create(UserCentryFragment.this)
                                .openCamera(PictureMimeType.ofImage()) //拍照
                                .imageEngine(UserImageEngine.createGlideEngine())
                                .isEnableCrop(true)//裁剪
                                .selectionMode(PictureConfig.SINGLE) //单张照片
//                                .circleDimmedLayer(true) //圆形裁剪框
//                                .setCircleStrokeWidth(3) //圆形裁剪框的宽度
                                .showCropFrame(true) //不显示矩形裁剪框
                                .hideBottomControls(true) //隐藏裁剪工具栏
                                .compress(true) //压缩图片
                                .minimumCompressSize(100) //小于100kb不压缩
                                .withAspectRatio(1, 1)//压缩比例
                                .cropImageWideHigh(170, 170)//裁剪宽高
                                .forResult(new OnResultCallbackListener<LocalMedia>() {
                                    @Override
                                    public void onResult(List<LocalMedia> result) {
                                        LocalMedia localMedia = result.get(0);
                                        String path = "";
                                        if (localMedia.isCut()) {//是否裁剪
                                            path = localMedia.getCutPath();
//                                            Glide.with(UserCentryFragment.this).load(localMedia.getCutPath()).into(viewDataBinding.userPersonIcon);
                                        } else {
                                            path = localMedia.getRealPath();
//                                            Glide.with(UserCentryFragment.this).load(localMedia.getRealPath()).into(viewDataBinding.userPersonIcon);
                                        }
                                        String finalPath = path;
                                        Glide.with(UserCentryFragment.this).asBitmap().load(path).into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                bitmap = resource;
//                                                viewDataBinding.userPersonIcon.setImageBitmap(bitmap);
                                                File file = new File(finalPath);
//                                                Log.d("myTAG", "onResourceReady: 111111111111");
                                                HeadIconUploadService.upload(bitmap, 0, null, new SimpleCallBack<UserIconBean>() {
                                                    @Override
                                                    public void onError(ApiException e) {
//                        Log.d("myTAG", "onError: ", e);
                                                        e.printStackTrace();
                                                        ToastUtils.showShort(e.getMessage());
                                                    }

                                                    @Override
                                                    public void onSuccess(UserIconBean bean) {
                                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.IMAGE_ICON_SIGN, System.currentTimeMillis() + "");
                                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.IMAGE_ICON, bean.getHeadPortraitUrl());
                                                        UserInfo userInfo = MmkvHelper.getInstance().getMmkv().decodeParcelable(Gobal.SAVE_KEY.USR_INFO, UserInfo.class);
                                                        userInfo.userImg = bean.getHeadPortraitUrl();
                                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.USR_INFO, userInfo);
                                                        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.IMAGE_ICON_CHANGE, Integer.class).postValue(1);//IMAGE_ICON_CHANGE  DEV_COUNT_CHANGE
//                        Log.d("myTAG", "onSuccess: 成功 o.tips：" + o.tips);
                                                    }

                                                    @Override
                                                    public void onTokenExpire() {
//                        Log.d("myTAG", "onTokenExpire: token过期");
                                                    }
                                                });
                                            }
                                        });
                                    }

                                    @Override
                                    public void onCancel() {
                                        //取消选择
//                                        Log.d("myTAG", "onCancel: 取消选择图片");
                                    }
                                });
                        popupWindow.dismiss();
                    }
                });
                //从相册中选择
                tvAlbum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PictureSelector.create(UserCentryFragment.this)
                                .openGallery(PictureMimeType.ofImage())  //打开相册
                                .imageEngine(UserImageEngine.createGlideEngine())
                                .selectionMode(PictureConfig.SINGLE) //单选模式
                                .isEnableCrop(true) //可以裁剪
//                                .circleDimmedLayer(true) //圆形裁剪框
//                                .setCircleStrokeWidth(3) //圆形裁剪框宽度
                                .showCropFrame(true) //不显示矩形裁剪框
                                .hideBottomControls(true) //隐藏裁剪工具栏
                                .compress(true) //压缩图片
                                .minimumCompressSize(10) //大于100kb都要压缩
                                .withAspectRatio(1, 1)//裁剪比例
                                .cropImageWideHigh(170, 170)//裁剪宽高
                                .forResult(new OnResultCallbackListener<LocalMedia>() {
                                    @Override
                                    public void onResult(List<LocalMedia> result) {
                                        LocalMedia localMedia = result.get(0);
                                        String path = "";
                                        if (localMedia.isCut()) {//是否裁剪
                                            path = localMedia.getCutPath();
//                                            Glide.with(UserCentryFragment.this).load(localMedia.getCutPath()).into(viewDataBinding.userPersonIcon);
                                        } else {
                                            path = localMedia.getRealPath();
//                                            Glide.with(UserCentryFragment.this).load(localMedia.getRealPath()).into(viewDataBinding.userPersonIcon);
                                        }
                                        String finalPath = path;
                                        Glide.with(UserCentryFragment.this).asBitmap().load(path).into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                bitmap = resource;
//                                                viewDataBinding.userPersonIcon.setImageBitmap(bitmap);
//                                                Log.d("myTAG", "onResourceReady: 11111111111111111111");
                                                HeadIconUploadService.upload(bitmap, 0 , null, new SimpleCallBack<UserIconBean>() {
                                                    @Override
                                                    public void onError(ApiException e) {
//                        Log.d("myTAG", "onError: ", e);
                                                        e.printStackTrace();
                                                        ToastUtils.showShort(e.getMessage());
                                                    }

                                                    @Override
                                                    public void onSuccess(UserIconBean bean) {
                                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.IMAGE_ICON_SIGN, System.currentTimeMillis() + "");
                                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.IMAGE_ICON, bean.getHeadPortraitUrl());
                                                        UserInfo userInfo = MmkvHelper.getInstance().getMmkv().decodeParcelable(Gobal.SAVE_KEY.USR_INFO, UserInfo.class);
                                                        userInfo.userImg = bean.getHeadPortraitUrl();
                                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.USR_INFO, userInfo);
                                                        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.IMAGE_ICON_CHANGE, Integer.class).postValue(1);//IMAGE_ICON_CHANGE  DEV_COUNT_CHANGE
//                        Log.d("myTAG", "onSuccess: 成功 o.tips：" + o.tips);
                                                    }

                                                    @Override
                                                    public void onTokenExpire() {
//                        Log.d("myTAG", "onTokenExpire: token过期");
                                                    }
                                                });
                                            }
                                        });
                                    }

                                    @Override
                                    public void onCancel() {
//                                        Log.d("myTAG", "onCancel: 取消选择图片");
                                        //取消
                                    }
                                });
                        popupWindow.dismiss();
                    }
                });
                //关闭弹出
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });

            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        ((UserSettingActivity) getActivity()).setTitle(getString(R.string.user_person_centry));
    }

    @Override
    public int getLayoutId() {
        return R.layout.user_centry_fragment;
    }

    @Override
    public int getBindingVariable() {
        return BR.data;
    }

    @Override
    protected UserCentryViewModel getViewModel() {
        userInfo = MmkvHelper.getInstance().getMmkv().decodeParcelable(Gobal.SAVE_KEY.USR_INFO, UserInfo.class);
        UserCentryViewModel tmp = new ViewModelProvider(this).get(UserCentryViewModel.class);
        tmp.setHeadUrlValue(userInfo.userImg);
        if (TextUtils.isEmpty(userInfo.userName)) {
            tmp.setNickValue(getString(R.string.user_nick));
        } else {
            tmp.setNickValue(userInfo.userName);
        }

        tmp.setSexTypeValue(userInfo.userSexType);
        return tmp;
    }

    @Override
    protected void onRetryBtnClick() {

    }
}
